/**
 * 状态管理器
 * 提供全局状态管理和状态同步功能
 */
class StateManager {
    constructor() {
        this.state = {};
        this.subscribers = new Map();
        this.history = [];
        this.maxHistorySize = 50;
        this.isUpdating = false;
        this.updateQueue = [];
        
        // 初始化默认状态
        this.initDefaultState();
        
        // 绑定事件监听器
        this.bindEventListeners();
    }
    
    /**
     * 初始化默认状态
     */
    initDefaultState() {
        this.state = {
            // 应用状态
            app: {
                isLoading: false,
                isOnline: navigator.onLine,
                theme: localStorage.getItem('theme') || 'light',
                sidebarCollapsed: localStorage.getItem('sidebarCollapsed') === 'true',
                currentRoute: window.location.hash.slice(1) || '/',
                breadcrumbs: [],
                notifications: []
            },
            
            // 用户状态 (用户中心功能已移除)
            // user: {
            //     isAuthenticated: false,
            //     username: localStorage.getItem('username') || '',
            //     permissions: JSON.parse(localStorage.getItem('permissions') || '[]'),
            //     preferences: JSON.parse(localStorage.getItem('userPreferences') || '{}')
            // }
            
            // 数据状态
            data: {
                links: [],
                stats: {},
                charts: {},
                cache: new Map()
            },
            
            // UI状态
            ui: {
                activeNavItem: '',
                openModals: [],
                loadingComponents: new Set(),
                errorComponents: new Set()
            },
            
            // 系统状态
            system: {
                lastUpdate: Date.now(),
                version: '1.0.0',
                performance: {
                    pageLoadTime: 0,
                    apiResponseTime: 0,
                    memoryUsage: 0
                }
            }
        };
    }
    
    /**
     * 绑定事件监听器
     */
    bindEventListeners() {
        // 监听在线状态变化
        window.addEventListener('online', () => {
            this.setState('app.isOnline', true);
        });
        
        window.addEventListener('offline', () => {
            this.setState('app.isOnline', false);
        });
        
        // 监听存储变化
        window.addEventListener('storage', (e) => {
            this.handleStorageChange(e);
        });
        
        // 监听页面可见性变化
        document.addEventListener('visibilitychange', () => {
            this.handleVisibilityChange();
        });
    }
    
    /**
     * 获取状态
     */
    getState(path) {
        if (!path) return this.state;
        
        const keys = path.split('.');
        let current = this.state;
        
        for (const key of keys) {
            if (current && typeof current === 'object' && key in current) {
                current = current[key];
            } else {
                return undefined;
            }
        }
        
        return current;
    }
    
    /**
     * 设置状态
     */
    setState(path, value, options = {}) {
        const { silent = false, history = true, immediate = false } = options;
        
        if (immediate) {
            this.updateState(path, value, { silent, history });
        } else {
            this.queueUpdate(path, value, { silent, history });
        }
    }
    
    /**
     * 队列更新
     */
    queueUpdate(path, value, options) {
        this.updateQueue.push({ path, value, options });
        
        if (!this.isUpdating) {
            this.processUpdateQueue();
        }
    }
    
    /**
     * 处理更新队列
     */
    processUpdateQueue() {
        if (this.updateQueue.length === 0) {
            this.isUpdating = false;
            return;
        }
        
        this.isUpdating = true;
        const update = this.updateQueue.shift();
        
        this.updateState(update.path, update.value, update.options);
        
        // 使用 requestAnimationFrame 优化性能
        requestAnimationFrame(() => {
            this.processUpdateQueue();
        });
    }
    
    /**
     * 更新状态
     */
    updateState(path, value, options) {
        const { silent = false, history = true } = options;
        
        const oldValue = this.getState(path);
        
        // 如果值没有变化，不触发更新
        if (this.isEqual(oldValue, value)) {
            return;
        }
        
        // 更新状态
        const keys = path.split('.');
        const lastKey = keys.pop();
        let current = this.state;
        
        for (const key of keys) {
            if (!current[key] || typeof current[key] !== 'object') {
                current[key] = {};
            }
            current = current[key];
        }
        
        current[lastKey] = value;
        
        // 记录历史
        if (history) {
            this.addToHistory(path, oldValue, value);
        }
        
        // 持久化到本地存储
        this.persistState(path, value);
        
        // 通知订阅者
        if (!silent) {
            this.notifySubscribers(path, value, oldValue);
        }
        
        // 更新最后更新时间
        this.state.system.lastUpdate = Date.now();
    }
    
    /**
     * 订阅状态变化
     */
    subscribe(path, callback, options = {}) {
        const { immediate = false, once = false } = options;
        
        if (!this.subscribers.has(path)) {
            this.subscribers.set(path, []);
        }
        
        const subscription = {
            callback,
            once,
            id: Date.now() + Math.random()
        };
        
        this.subscribers.get(path).push(subscription);
        
        // 立即触发回调
        if (immediate) {
            const currentValue = this.getState(path);
            callback(currentValue, undefined, path);
        }
        
        return () => this.unsubscribe(path, subscription.id);
    }
    
    /**
     * 取消订阅
     */
    unsubscribe(path, subscriptionId) {
        if (!this.subscribers.has(path)) {
            return;
        }
        
        const subscriptions = this.subscribers.get(path);
        const index = subscriptions.findIndex(sub => sub.id === subscriptionId);
        
        if (index !== -1) {
            subscriptions.splice(index, 1);
        }
        
        if (subscriptions.length === 0) {
            this.subscribers.delete(path);
        }
    }
    
    /**
     * 通知订阅者
     */
    notifySubscribers(path, newValue, oldValue) {
        // 通知具体路径的订阅者
        if (this.subscribers.has(path)) {
            const subscriptions = this.subscribers.get(path);
            const toRemove = [];
            
            subscriptions.forEach((subscription, index) => {
                try {
                    subscription.callback(newValue, oldValue, path);
                    
                    if (subscription.once) {
                        toRemove.push(index);
                    }
                } catch (error) {
                    console.error('State subscription error:', error);
                    toRemove.push(index);
                }
            });
            
            // 移除一次性订阅
            toRemove.reverse().forEach(index => {
                subscriptions.splice(index, 1);
            });
        }
        
        // 通知通配符订阅者
        if (this.subscribers.has('*')) {
            const wildSubscriptions = this.subscribers.get('*');
            const toRemove = [];
            
            wildSubscriptions.forEach((subscription, index) => {
                try {
                    subscription.callback(newValue, oldValue, path);
                    
                    if (subscription.once) {
                        toRemove.push(index);
                    }
                } catch (error) {
                    console.error('State wildcard subscription error:', error);
                    toRemove.push(index);
                }
            });
            
            toRemove.reverse().forEach(index => {
                wildSubscriptions.splice(index, 1);
            });
        }
    }
    
    /**
     * 添加到历史记录
     */
    addToHistory(path, oldValue, newValue) {
        const historyEntry = {
            path,
            oldValue: this.deepClone(oldValue),
            newValue: this.deepClone(newValue),
            timestamp: Date.now()
        };
        
        this.history.push(historyEntry);
        
        // 限制历史记录大小
        if (this.history.length > this.maxHistorySize) {
            this.history.shift();
        }
    }
    
    /**
     * 持久化状态
     */
    persistState(path, value) {
        // 只持久化特定路径的状态 (用户中心功能已移除)
        const persistPaths = [
            'app.theme',
            'app.sidebarCollapsed'
            // 'user.username',
            // 'user.preferences'
        ];
        
        if (persistPaths.includes(path)) {
            try {
                localStorage.setItem(path, JSON.stringify(value));
            } catch (error) {
                console.warn('Failed to persist state:', error);
            }
        }
    }
    
    /**
     * 处理存储变化
     */
    handleStorageChange(event) {
        if (event.key && event.key.startsWith('app.')) {
            try {
                const newValue = JSON.parse(event.newValue);
                this.setState(event.key, newValue, { silent: true, history: false });
            } catch (error) {
                console.warn('Failed to handle storage change:', error);
            }
        }
    }
    
    /**
     * 处理页面可见性变化
     */
    handleVisibilityChange() {
        if (document.hidden) {
            // 页面隐藏时暂停非必要的更新
            this.isUpdating = false;
        } else {
            // 页面显示时恢复更新
            this.processUpdateQueue();
        }
    }
    
    /**
     * 批量更新状态
     */
    batchUpdate(updates) {
        const batchId = Date.now();
        
        updates.forEach(({ path, value, options = {} }) => {
            this.setState(path, value, { ...options, silent: true });
        });
        
        // 批量通知
        this.notifySubscribers('*', this.state, null);
    }
    
    /**
     * 重置状态
     */
    resetState(path) {
        if (path) {
            const defaultState = this.getDefaultValue(path);
            this.setState(path, defaultState);
        } else {
            this.initDefaultState();
            this.notifySubscribers('*', this.state, null);
        }
    }
    
    /**
     * 获取默认值
     */
    getDefaultValue(path) {
        const defaultState = {
            'app.isLoading': false,
            'app.isOnline': navigator.onLine,
            'app.theme': 'light',
            'app.sidebarCollapsed': false,
            'ui.activeNavItem': '',
            'ui.loadingComponents': new Set(),
            'ui.errorComponents': new Set()
        };
        
        return defaultState[path];
    }
    
    /**
     * 获取状态历史
     */
    getHistory(path, limit = 10) {
        if (!path) {
            return this.history.slice(-limit);
        }
        
        return this.history
            .filter(entry => entry.path === path)
            .slice(-limit);
    }
    
    /**
     * 清除历史
     */
    clearHistory() {
        this.history = [];
    }
    
    /**
     * 深度比较
     */
    isEqual(a, b) {
        if (a === b) return true;
        
        if (a == null || b == null) return false;
        
        if (typeof a !== typeof b) return false;
        
        if (typeof a !== 'object') return false;
        
        if (a instanceof Set && b instanceof Set) {
            return a.size === b.size && [...a].every(item => b.has(item));
        }
        
        if (a instanceof Map && b instanceof Map) {
            if (a.size !== b.size) return false;
            for (let [key, value] of a) {
                if (!b.has(key) || !this.isEqual(value, b.get(key))) {
                    return false;
                }
            }
            return true;
        }
        
        const keysA = Object.keys(a);
        const keysB = Object.keys(b);
        
        if (keysA.length !== keysB.length) return false;
        
        for (let key of keysA) {
            if (!keysB.includes(key)) return false;
            if (!this.isEqual(a[key], b[key])) return false;
        }
        
        return true;
    }
    
    /**
     * 深度克隆
     */
    deepClone(obj) {
        if (obj === null || typeof obj !== 'object') return obj;
        
        if (obj instanceof Date) return new Date(obj.getTime());
        
        if (obj instanceof Array) return obj.map(item => this.deepClone(item));
        
        if (obj instanceof Set) return new Set([...obj].map(item => this.deepClone(item)));
        
        if (obj instanceof Map) {
            const clonedMap = new Map();
            for (let [key, value] of obj) {
                clonedMap.set(this.deepClone(key), this.deepClone(value));
            }
            return clonedMap;
        }
        
        const clonedObj = {};
        for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
                clonedObj[key] = this.deepClone(obj[key]);
            }
        }
        
        return clonedObj;
    }
    
    /**
     * 销毁
     */
    destroy() {
        this.subscribers.clear();
        this.history = [];
        this.updateQueue = [];
        this.isUpdating = false;
    }
}

// 创建全局状态管理器实例
window.StateManager = new StateManager();